import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import { emitter } from '@/utils/bus'
import router from '@/router/index'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 600 // 请求超时时间
})
let acitveAxios = 0
let timer
const showLoading = () => {
  acitveAxios++
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    if (acitveAxios > 0) {
      emitter.emit('showLoading')
    }
  }, 400)
}

const closeLoading = () => {
  acitveAxios--
  if (acitveAxios <= 0) {
    clearTimeout(timer)
    emitter.emit('closeLoading')
  }
}

// http request 拦截器
request.interceptors.request.use(
    config => {
      if (!config.donNotShowLoading) {
        showLoading()
      }
      const userStore = useUserStore()
      config.headers = {
        'Content-Type': 'application/json',
        'token': userStore.token,
        ...config.headers
      }
      return config
    },
    error => {
      closeLoading()
      ElMessage({
        showClose: true,
        message: error,
        type: 'error'
      })
      return error
    }
  )
  
// http response 拦截器
request.interceptors.response.use(
    response => {
      const userStore = useUserStore()
      closeLoading()
      if (response.headers['new-token']) {
        userStore.setToken(response.headers['token'])
      }
      return response
    },
    error => {
      closeLoading()
  
      if(!error.response){
        ElMessageBox.confirm(`
          <p>检测到请求错误</p>
          <p>${error}</p>
          `, '请求报错', {
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            confirmButtonText: '稍后重试',
            cancelButtonText: '取消'
          })
          return error.response
      }
  
      switch (error.response.status) {
        case 500:
          ElMessageBox.confirm(`
          <p>检测到接口错误${error}</p>
          <p>错误码<span style="color:red"> 500 </span>：此类错误内容常见于后台panic，请先查看后台日志，如果影响您正常使用可强制登出清理缓存</p>
          `, '接口报错', {
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            confirmButtonText: '清理缓存',
            cancelButtonText: '取消'
          })
            .then(() => {
              const userStore = useUserStore()
              userStore.token = ''
              localStorage.clear()
              router.push({ name: 'login'})
            })
          break
        case 404:
          ElMessageBox.confirm(`
            <p>检测到接口错误${error}</p>
            <p>错误码<span style="color:red"> 404 </span>：此类错误多为接口未注册（或未重启）或者请求路径（方法）与api路径（方法）不符--如果为自动化代码请检查是否存在空格</p>
            `, '接口报错', {
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            confirmButtonText: '我知道了',
            cancelButtonText: '取消'
          })
          break
        case 400:
            ElMessage({
                type: 'fail',
                message:error
              })
            break
      }
  
      return error.response
    }
  )
  
export default request
